<?php

namespace serv\queue\warehouse;

use of;
use L;
use of\base\com\mq;
use common\batchInsert;
use common\commonUpdateTrait;
use Eccang\OpenApi\Contracts\Config;
use Eccang\OpenApi\Eccang as callApi;
use Eccang\OpenApi\System\Request\AppUnityRequest;
use traits\StockTrait;


class eccang
{
    //同步库位库存信息
    public static function pull($data)
    {
        set_time_limit(0);
        $param = $data['data'];
        try {
            $page_size = 500;
            $current_page = 1;
            do {
                $data = [
                    'page' => $current_page,
                    'page_size' => $page_size
                ];
                $data = array_merge($data, $param);
                $response = self::callApi('getProductInventoryForLocation', $data);
                if (200 == $response['code']) {
                    if (!empty($response['data']->getBody())) {
                        //表接口获取回来的仓库列表同步的数据库
                        $rows = $response['data']->getBody();
                        //启动队列去检查并同步
                        foreach ($rows['biz_content'] as $v) {
                            $key = "check_eccang_sku_stock_{$v['lc_code']}_{$v['product_sku']}";
                            $v = array_merge($v, ['warehouse_id' => $param['warehouse_id']]);
                            //echo json_encode($v, JSON_UNESCAPED_UNICODE); exit;
                            mq::set(["checkEccangSkuStock", $key], $v);
                        }
                        $total_page = ceil($response['data']->getTotal() / $page_size);
                    } else {
                        $total_page = 1;
                    }
                } else {
                    $total_page = 1;
                }
                $current_page++;
            } while ($current_page <= $total_page);

            return true;
        } catch (Exception $exp) {
            return false;
        }
    }

    //库存信息处理
    public static function checkStock($arr)
    {
        set_time_limit(0);
        try {
            of::work(['warehouse']);
            $val = $arr['data'];
            $sql = "SELECT stock_id FROM stock WHERE 1 
                    AND warehouse_id = '{$val['warehouse_id']}' 
                    AND sku_code = '{$val['product_sku']}';";
            $result = L::sql($sql, 'warehouse');
            if (!empty($result)) {
                //更新数据
                $data = [
                    'sku' => StockTrait::tran2sku($val['product_sku']),
                    'available_stock' => $val['quantity'],
                    'lock_stock' => $val['out_quantity'],
                    'stock' => $val['quantity'] + $val['out_quantity'],
                    'status' => StockTrait::stockStatus($val['product_sku']),
                    'belong' => of::config('env.PUBLIC_BELONG'),
                    'updated_by' => of::config('env.SYSTEM_ID'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                //更新
                commonUpdateTrait::update('stock', $data, $result[0]['stock_id'], 'stock_id');
            } else {
                //插入数据
                $position = self::position($val['lc_code']);
                $data[] = [
                    'position_id' => !empty($position) ? $position['position_id'] : 1,
                    'area_id' => !empty($position) ? $position['area_id'] : 1,
                    'warehouse_id' => $val['warehouse_id'],
                    'sku' => StockTrait::tran2sku($val['product_sku']),
                    'sku_code' => $val['product_sku'],
                    'sku_name' => $val['product_sku_title'],
                    'sku_name_en' => $val['product_sku_en_title'],
                    'stock' => $val['quantity'] + $val['out_quantity'],
                    'available_stock' => $val['quantity'],
                    'lock_stock' => $val['out_quantity'],
                    'on_way_stock' => 0,
                    'status' => StockTrait::stockStatus($val['product_sku']),
                    'belong' => of::config('env.PUBLIC_BELONG'),
                    'created_by' => of::config('env.SYSTEM_ID'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_by' => of::config('env.SYSTEM_ID'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                $sql = batchInsert::insert('stock', $data);
                L::sql($sql, 'warehouse');
            }
            of::work(true);
            return true;
        } catch (Exception $exp) {
            of::work($exp);
            return false;
        }
    }


    //检查仓库是否已存在，不存在则写入，存在则更新
    public static function warehouseList($arr)
    {
        try {
            of::work(['warehouse']);
            $val = $arr['data'];
            $sql = "SELECT id FROM warehouse WHERE 1 AND warehouse_id = '{$val['warehouse_id']}';";
            $result = L::sql($sql, 'warehouse');
            if (!empty($result)) {
                //更新数据
                $data = [
                    'name' => $val['warehouse_name'],
                    'name_en' => $val['warehouse_name'],
                    'status' => $val['warehouse_status'],
                    'sync' => 0,
                    'updated_by' => of::config('env.SYSTEM_ID'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                //更新
                commonUpdateTrait::update('warehouse', $data, $result[0]['id']);
            } else {
                //插入数据
                $data[] = [
                    'warehouse_id' => $val['warehouse_id'],
                    'name' => $val['warehouse_name'],
                    'name_en' => $val['warehouse_name'],
                    'warehouse_code' => $val['warehouse_code'],
                    'warehouse_type' => $val['warehouse_type'],
                    'status' => $val['warehouse_status'],
                    'sync' => 0,
                    'type' => 20,
                    'created_by' => of::config('env.SYSTEM_ID'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_by' => of::config('env.SYSTEM_ID'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                $sql = batchInsert::insert('warehouse', $data);
                L::sql($sql, 'warehouse');
            }
            of::work(true);
            return true;
        } catch (Exception $exp) {
            of::work($exp);
            return false;
        }
    }

    //获取仓库详情
    public static function warehouseDetail($arr)
    {
        set_time_limit(0);
        try {
            of::work(['warehouse']);
            $data = $arr['data'];
            $response = self::callApi('getWarehouse', $data);
            if (!empty($response['data']->getData())) {
                $array = $response['data']->getData();;
                foreach ($array as $key => $val) {
                    $data = [
                        'country' => $val['country_code'],
                        'province' => $val['state'],
                        'city' => $val['city'],
                        'address' => addslashes($val['street_address1'] . ' '.$val['street_address2']),
                        'postcode' => $val['postcode'],
                        'warehouse_region' => $val['country_code'],
                        'virtual' => $val['warehouse_virtual'],
                        'warehouse_service' => $val['warehouse_service'],
                        'is_transfer' => $val['is_transfer'],
                        'sync' => 1,
                        'updated_by' => of::config('env.SYSTEM_ID'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    //更新仓库详情
                    commonUpdateTrait::update('warehouse', $data, $val['warehouse_id'], 'warehouse_id');
                }
            }
            of::work(true);
            return true;
        } catch (Exception $exp) {
            of::work($exp);
            return false;
        }
    }

    //区域列表
    public static function areaList($arr)
    {
        set_time_limit(0);
        try {
            $param = $arr['data'];
            $page_size = 100;
            $current_page = 1;
            do {
                $data = [
                    'warehouse_id' => $param['warehouse_id'],
                    'page' => $current_page,
                    'page_size' => $page_size
                ];
                $response = self::callApi('getWarehouseArea', $data);
                if (200 == $response['code']) {
                    if (!empty($response['data']->getData())) {
                        $rows = $response['data']->getData();
                        self::checkArea($rows);
                        $total_page = ceil($response['data']->getTotal() / $page_size);
                    } else {
                        $total_page = 1;
                    }
                } else {
                    $total_page = 1;
                }
                $current_page++;
            } while ($current_page <= $total_page);

            return true;
        } catch (Exception $exp) {
            return false;
        }
    }

    //同步库位
    public static function positionList($arr)
    {
        set_time_limit(0);
        try {
            $param = $arr['data'];
            $page_size = 100;
            $current_page = 1;
            do {
                $data = [
                    'page' => $current_page,
                    'page_size' => $page_size
                ];
                $data = array_merge($data, $param);
                $response = self::callApi('getWarehouseLocation', $data);
                if (200 == $response['code']) {
                    if (!empty($response['data']->getData())) {
                        $rows = $response['data']->getData();
                        self::checkPosition($rows);
                        $total_page = ceil($response['data']->getTotal() / $page_size);
                    } else {
                        $total_page = 1;
                    }
                } else {
                    $total_page = 1;
                }
                $current_page++;
            } while ($current_page <= $total_page);

            return true;
        } catch (Exception $exp) {
            return false;
        }
    }

    //把从易仓同步回来的订单信息存储到数据库
    public static function orderWarehouse($arr)
    {
        set_time_limit(0);
        try {
            of::work(['warehouse']);
            $data = $arr['data'];
            $sql = "SELECT id FROM order_warehouse WHERE 1 AND refrence_no_sys = '{$data['refrence_no_sys']}';";
            $result = L::sql($sql, 'warehouse');
            if (empty($result)) {
                //插入数据
                $warehouseData[] = [
                    'warehouse_code' => $data['warehouse_code'],
                    'warehouse_id' => $data['warehouse_id'],
                    'warehouse_ship_date' => $data['warehouse_ship_date'],
                    'date_create_sys' => $data['date_create_sys'],
                    'shipping_method' => $data['shipping_method'],
                    'shipping_method_no' => $data['shipping_method_no'],
                    'platform_paid_date' => $data['platform_paid_date'],
                    'date_create_platform' => $data['date_create_platform'],
                    'refrence_no_sys' => $data['refrence_no_sys'],
                    'order_code' => $data['order_code'],
                    'platform' => $data['platform'],
                    'warehouse_order_code' => isset($data['warehouse_order_code']) ? $data['warehouse_order_code'] : '',
                    'status' => 0
                ];
                $sql = batchInsert::insert('order_warehouse', $warehouseData);
                $orderId = L::sql($sql, 'warehouse');
                if ($orderId) {
                    //插入订单明细
                    $orderDetails = [];
                    foreach ($data['order_details'] as $dv) {
                        foreach ($dv['warehouse_sku_list'] as $wv) {
                            $orderDetails[] = [
                                'order_id' => $orderId,
                                'team_id' => $dv['team_id'],
                                'team_name' => $dv['team_name'],
                                'warehouse_sku' => $wv['warehouse_sku'],
                                'warehouse_sku_qty' => $wv['warehouse_sku_qty']
                            ];
                        }
                    }
                    $sql = batchInsert::insert('order_warehouse_detail', $orderDetails);
                    L::sql($sql, 'warehouse');
                }
            }
            of::work(true);
            return true;
        } catch (Exception $exp) {
            of::work($exp);
            return false;
        }
    }


    /*
     * 因为易仓的SDK 接口基本都是传调用的方法及请求参数，故封闭成一个方法供其它类调用即可
     *
     */
    private static function callApi($method, $bizContent)
    {
        try {
            $config = new Config();
            $config->setAppKey(of::config('env.ECCANG.appKey'))
                ->setServiceId(of::config('env.ECCANG.serviceId'))
                ->setAppScrete(of::config('env.ECCANG.secret'))
                ->setNonceStr(time());
            $request = new AppUnityRequest();
            $request->setInterfaceMethod($method)
                ->setBizContent($bizContent);
            return [
                'code' => 200,
                'data' => callApi::system($config)->appUnity($request),
                'message' => ''
            ];
        } catch (\Exception $exception) {
            return [
                'code' => 500,
                'data' => [],
                'message' => $exception->getMessage()
            ];
        }
    }

    private static function checkArea($rows)
    {
        if (!empty($rows)) {
            foreach ($rows as $key => $val) {
                $data = [];
                $sql = "SELECT area_id FROM area WHERE 1 AND wa_code = '{$val['wa_code']}';";
                $result = L::sql($sql, 'warehouse');
                if (!empty($result)) {
                    //更新数据
                    $data = [
                        'wa_code' => $val['wa_code'],
                        'wa_name' => $val['wa_name'],
                        'wa_name_en' => $val['wa_name_en'],
                        'wa_type' => $val['wa_type'],
                        'wa_status' => $val['wa_status'],
                        'wa_inventory_type' => $val['wa_inventory_type'],
                        'updated_by' => of::config('env.SYSTEM_ID'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    //更新
                    commonUpdateTrait::update('area', $data, $result[0]['area_id'], 'area_id');
                } else {
                    //插入数据
                    $data[] = [
                        'warehouse_id' => $val['warehouse_id'],
                        'wa_code' => $val['wa_code'],
                        'wa_name' => $val['wa_name'],
                        'wa_name_en' => $val['wa_name_en'],
                        'wa_type' => $val['wa_type'],
                        'wa_status' => $val['wa_status'],
                        'wa_inventory_type' => $val['wa_inventory_type'],
                        'created_by' => of::config('env.SYSTEM_ID'),
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_by' => of::config('env.SYSTEM_ID'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    $sql = batchInsert::insert('area', $data);
                    L::sql($sql, 'warehouse');
                }
            }
        }
    }

    //检查库位
    private static function checkPosition($rows)
    {
        if (!empty($rows)) {
            foreach ($rows as $key => $val) {
                $data = [];
                $sql = "SELECT position_id FROM `position` WHERE 1 AND lc_code = '{$val['lc_code']}';";
                $result = L::sql($sql, 'warehouse');
                $area = self::area($val['wa_code']);
                if (!empty($result)) {
                    //更新数据
                    $data = [
                        'area_id' => !empty($area) ? $area['area_id'] : 1,
                        'lc_code' => $val['lc_code'],
                        'lc_note' => $val['lc_note'],
                        'lc_status' => $val['lc_status'],
                        'lt_code' => $val['lt_code'],
                        'warehouse_id' => $val['warehouse_id'],
                        'wa_code' => $val['wa_code'],
                        'wa_name' => $val['wa_name'],
                        'wa_name_en' => $val['wa_name_en'],
                        'updated_by' => of::config('env.SYSTEM_ID'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    //更新
                    commonUpdateTrait::update('position', $data, $result[0]['position_id'], 'position_id');
                } else {
                    //插入数据
                    $data[] = [
                        'area_id' => !empty($area) ? $area['area_id'] : 1,
                        'lc_code' => $val['lc_code'],
                        'lc_note' => $val['lc_note'],
                        'lc_status' => $val['lc_status'],
                        'lt_code' => $val['lt_code'],
                        'warehouse_id' => $val['warehouse_id'],
                        'wa_code' => $val['wa_code'],
                        'wa_name' => $val['wa_name'],
                        'wa_name_en' => $val['wa_name_en'],
                        'wa_type' => $val['wa_type'],
                        'created_by' => of::config('env.SYSTEM_ID'),
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_by' => of::config('env.SYSTEM_ID'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    $sql = batchInsert::insert('position', $data);
                    L::sql($sql, 'warehouse');
                }
            }
        }
    }

    //根据区域获取区域id
    private static function area($wa_code)
    {
        $sql = "SELECT area_id FROM `area` WHERE 1 AND wa_code = '{$wa_code}';";
        $rows = L::sql($sql, 'warehouse');
        return (!empty($rows)) ? $rows[0] : [];
    }

    //根据库位代码获取库位及区域id
    private static function position($lc_code)
    {
        $sql = "SELECT position_id, area_id FROM `position` WHERE 1 AND lc_code = '{$lc_code}';";
        $rows = L::sql($sql, 'warehouse');
        return (!empty($rows)) ? $rows[0] : [];
    }

}
